package com.juku2024.juku.fragment

import android.text.TextUtils
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.util.getOrDefault
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.juku2024.juku.R
import com.juku2024.juku.VideoDetailActivity
import com.juku2024.juku.adapter.CategoryListAdapter
import com.juku2024.juku.adapter.CategorySearchTagItemAdapter
import com.juku2024.juku.base.BaseFragment
import com.juku2024.juku.callback.OnSearchKeySelectedCallback
import com.juku2024.juku.model.CategorySearchModel
import com.juku2024.juku.model.CategorySearchTagModel
import com.juku2024.juku.model.Genre
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.WrapGridLayoutManager
import com.juku2024.juku.tools.WrapLinearLayoutManager
import com.juku2024.juku.viewmodel.CategoryViewModel
import com.juku2024.juku.widget.CategorySearchTagView
import com.juku2024.juku.widget.LoadingView
import kotlin.collections.ArrayList
import kotlin.math.abs

class CategoryFragment : BaseFragment() {

    private var page: Int = 1
    private var classesId: Int = 2
    private var tagId: Int = 0
    private var yearId: Int = 0
    private var areaId: Int = 0
    private var tagModel: CategorySearchModel? = null
    private val adapter by lazy { CategoryListAdapter(ArrayList()) }
    private val categorySparse by lazy { SparseArray<CategorySearchModel?>() }
    private val classesAdapter by lazy { CategorySearchTagItemAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(requireActivity().viewModelStore, CategoryViewModel::class.java) }

    private lateinit var loadingView: LoadingView
    private lateinit var categoryRecycler: RecyclerView
    private lateinit var classesRecycler: RecyclerView
    private lateinit var searchKeyView: CategorySearchTagView
    private lateinit var appBarLayout: AppBarLayout
    private lateinit var tvTopTitle: TextView
    private lateinit var tagLayout: View

    override fun layoutView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_category, container, false)
    }

    override fun initView(rootView: View) {
        super.initView(rootView)
        loadingView = rootView.findViewById(R.id.loadingView)
        categoryRecycler = rootView.findViewById(R.id.categoryRecycler)
        classesRecycler = rootView.findViewById(R.id.classesRecycler)
        searchKeyView = rootView.findViewById(R.id.searchKeyView)
        appBarLayout = rootView.findViewById(R.id.appBarLayout)
        tvTopTitle = rootView.findViewById(R.id.tvTopTitle)
        tagLayout = rootView.findViewById(R.id.tagLayout)

        loadingView.showLoading()
        val gridLayoutManager = WrapGridLayoutManager(requireContext(), 3)
        categoryRecycler.layoutManager = gridLayoutManager
        categoryRecycler.adapter = adapter

        classesRecycler.layoutManager = WrapLinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL)
        classesRecycler.setHasFixedSize(true)
        classesRecycler.adapter = classesAdapter
    }

    override fun bindEvent() {
        super.bindEvent()
        searchKeyView.callback = object : OnSearchKeySelectedCallback {
            override fun onSearchKeySelected(classes: Int, tags: Int, year: Int, keyModel: CategorySearchTagModel?) {
                LogC.e("classes=$classes, tags=$tags, year=$year, name=${keyModel?.name}")
                loadingView.showLoading()
                // 设置顶部的搜索字段
                setTopSearchKey()
                adapter.setList(ArrayList())
                page = 1
                tagId = tags
                yearId = year
                // 更新缓存
                val cacheModel = categorySparse.get(classesId)
                cacheModel?.apply {
                    this.years?.firstOrNull { it.isSelected }?.isSelected = false
                    this.years?.firstOrNull { it.id == yearId }?.isSelected = true

                    this.tags?.firstOrNull { it.isSelected }?.isSelected = false
                    this.tags?.firstOrNull { it.id == tagId }?.isSelected = true
                }
                if (cacheModel != null) {
                    // 将入缓存
                    categorySparse.put(classesId, cacheModel)
                }

                // 每次搜索都清空列表
                loadingView.postDelayed({
                    doHttpGetSearchResult()
                }, 500)
            }
        }

        adapter.setOnItemClickListener { _, _, position ->
            // 统计进入详情的时候的标签
            VideoDetailActivity.toVideoDetail(requireContext(), adapter.data[position].id, adapter.data[position].name)
        }
        val statusBarHeight = context?.resources?.getDimensionPixelSize(R.dimen.status_bar_height) ?: 0
        appBarLayout.addOnOffsetChangedListener { appBarLayout, height ->
            val appBarMeasuredHeight = appBarLayout?.measuredHeight ?: 0
            tvTopTitle.alpha = abs(height - statusBarHeight) / (appBarMeasuredHeight * 1.0f)
            if (height < 0) {
                tvTopTitle.isClickable = true
                tvTopTitle.visibility = View.VISIBLE
            } else {
                tvTopTitle.isClickable = false
                tvTopTitle.visibility = View.GONE
            }
        }

        tvTopTitle.setOnClickListener {
            categoryRecycler.smoothScrollToPosition(0)
        }

        adapter.loadMoreModule.setOnLoadMoreListener {
            doHttpGetSearchResult()
        }

        classesAdapter.setOnItemClickListener { _, _, position ->
            val index = classesAdapter.data.indexOfFirst { it.isSelected }
            if (index != -1 && index != position) {
                // 修改ui
                classesAdapter.data[index].isSelected = false
                classesAdapter.notifyItemChanged(index)
                val currentItem = classesAdapter.data[position]
                currentItem.isSelected = true
                classesAdapter.notifyItemChanged(position)
                // 设置新的分类id
                classesId = currentItem.id
                // 清空结果列表
                adapter.setList(ArrayList())
                // 展示loading
                loadingView.showLoading()
                // 重置标签
                page = 1
                // 从缓存中取出当前分类的tag
                val cacheData = categorySparse.getOrDefault(classesId, null)
                if (cacheData == null) { // 没有缓存
                    // 清空搜索标签view内容
                    searchKeyView.release()
                    // 重新请求标签
                    doHttpCategorySearchTag()
                } else {
                    // 使用缓存的标签
                    searchKeyView.init(cacheData)
                    tagId = cacheData.tags?.firstOrNull { it.isSelected }?.id?:0
                    yearId = cacheData.years?.firstOrNull { it.isSelected }?.id?:0
                    // 设置选中的内容
                    setTopSearchKey()
                    // 查询当前的内容
                    doHttpGetSearchResult()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (tagLayout.visibility != View.GONE) return
        loadingView.showLoading()
        doGenreList()
    }

    private fun doGenreList() {
        viewModel.getGenreList({
            if (isFragmentNotActive()) return@getGenreList
            initGenre(it)

            doHttpCategorySearchTag()
        }, {
            if (isFragmentNotActive()) return@getGenreList
            loadingView.showErrorStatus(it, getString(R.string.retry)) {
                loadingView.showLoading()
                loadingView.postDelayed({
                    doGenreList()
                }, 500)
            }
        })
    }

    private fun initGenre(data: ArrayList<Genre>?) {
        val targetList = ArrayList<CategorySearchTagModel>()
        data?.filterIndexed { index, genre ->
            val tag = CategorySearchTagModel()
            if (index == 0) {
                classesId = genre.genre_id
                tag.isSelected = true
            }
            tag.name = genre.name
            tag.id = genre.genre_id
            targetList.add(tag)
        }
        classesAdapter.setList(targetList)
    }

    private fun doHttpCategorySearchTag() {
        viewModel.getSearchTagList(classesId, {
            if (isFragmentNotActive()) return@getSearchTagList
            tagModel = it
            initSearchTag()
            // 根据标签查询当前的内容
            doHttpGetSearchResult()
        }, {
            if (isFragmentNotActive()) return@getSearchTagList
            loadingView.showErrorStatus(it, getString(R.string.retry)) {
                loadingView.showLoading()
                loadingView.postDelayed({
                    doHttpCategorySearchTag()
                }, 500)
            }
        })
    }

    private fun initSearchTag() {
        tagLayout.visibility = View.VISIBLE
        // 根据分类内容来设置对应的数据
        if (classesAdapter.data.isEmpty()) {
            val first = tagModel?.classes?.firstOrNull()
            first?.isSelected = true
            classesId = first?.id ?: 2
            classesAdapter.setList(tagModel?.classes)
        }
        // 默认所有分类的第一个是选中状态
        if (tagModel?.years?.firstOrNull()?.name == "全部年份") {
            val yearSize = tagModel?.years?.size?:0
            if (yearSize >= 2) {
                tagModel?.years?.get(1)?.apply {
                    isSelected = true
                    yearId = id
                }
            } else {
                tagModel?.years?.firstOrNull()?.apply {
                    isSelected = true
                    yearId = id
                }
            }
        } else {
            tagModel?.years?.firstOrNull()?.apply {
                isSelected = true
                yearId = id
            }
        }

        tagModel?.tags?.firstOrNull()?.apply {
            isSelected = true
            tagId = id
        }
        tagModel?.classes = classesAdapter.data as java.util.ArrayList<CategorySearchTagModel>
        // 将入缓存
        categorySparse.put(classesId, tagModel)
        // 设置标签的内容
        searchKeyView.init(tagModel)
        // 设置top文本的内容
        setTopSearchKey()
        // 此时page肯定得 == 1
        page = 1
    }

    /**
     * 获取搜索关键字对应的列表
     */
    private fun doHttpGetSearchResult() {
        LogC.e("classes=$classesId, tags=$tagId, year=$yearId, area=$areaId, page=${page}")
        viewModel.getCategoryList(
            genreId = classesId,
            tagId = tagId,
            yearId = yearId,
            page = page, {
                if (isFragmentNotActive()) return@getCategoryList
                if (it.results.isNullOrEmpty()) {
                    loadingView.hideLoading()
                    if (adapter.data.isEmpty()) {
                        loadingView.showEmptyStatus(getString(R.string.empty_list))
                        adapter.loadMoreModule.loadMoreEnd(true)
                    } else {
                        adapter.loadMoreModule.loadMoreFail()
                    }
                    return@getCategoryList
                }
                if (adapter.data.isEmpty()) {
                    adapter.setList(it.results)
                } else {
                    adapter.addData(it.results)
                }

                if (TextUtils.isEmpty(it.next)) {
                    adapter.loadMoreModule.loadMoreEnd(adapter.data.size < 9)
                } else {
                    page++
                    adapter.loadMoreModule.loadMoreComplete()
                }

                loadingView.hideLoading()
            }, {
                loadingView.hideLoading()
                if (adapter.data.isEmpty()) {
                    loadingView.showEmptyStatus(getString(R.string.empty_list))
                } else {
                    adapter.loadMoreModule.loadMoreFail()
                }
            }
        )
    }

    private fun setTopSearchKey() {
        categorySparse.getOrDefault(classesId, null)?.apply {
            val topTitle = StringBuilder()
            val category = classes?.firstOrNull { it?.id == classesId }?.name
            if (!TextUtils.isEmpty(category)) {
                topTitle.append(category)
                topTitle.append("·")
            }
            adapter.isMovie = category == "电影"

            val tag = tags?.firstOrNull { it.isSelected }?.name
            if (!TextUtils.isEmpty(tag)) {
                topTitle.append(tag)
                topTitle.append("·")
            }
            val year = years?.firstOrNull { it.isSelected }?.name
            if (!TextUtils.isEmpty(year)) {
                topTitle.append(year)
            }
            tvTopTitle.text = topTitle.toString()
        }
    }
}